using BasicScript;
using Game.Main.Event;
using Game.Manager;
using System.Collections;
using System.Diagnostics;
using UnityEngine;

namespace Game.Core.Loader
{
	public class ResourceLoader : EventObject
	{
		public string path;

		public string resourceName;

		public Object resource;

		public object parameters;

		private bool dontDestroySprite;

		public ResourceLoader(string path, string resourceName, bool dontDestroySprite = false)
		{
			this.path = path.ToLower();
			this.resourceName = resourceName.ToLower();
			this.dontDestroySprite = dontDestroySprite;
		}

		public void Load()
		{
			if (path != null)
			{
				if (resource == null)
				{
					Client.Instance.AddResourceLoaderLoader(this);
				}
				else
				{
					Fire(new BaseEvent(LoadEvent.LOAD_COMPLETE));
				}
			}
			else
			{
				Fire(new BaseEvent(LoadEvent.LOAD_ERROR));
			}
		}

		public void BeginLoad()
		{
			Client.Instance.StartCoroutine(StartLoadResource());
		}

		private IEnumerator StartLoadResource()
		{
			string url = path;
			ResourceRequest request = Resources.LoadAsync(url);
            yield return request;

			bool isError = false;
			if (request == null || request.asset == null)
			{
				isError = true;
				Trace.LogWarning("资源加载失败：" + path);
				Fire(new BaseEvent(LoadEvent.LOAD_ERROR));
            }
			else
			{
				resource = request.asset;
                Fire(new BaseEvent(LoadEvent.LOAD_COMPLETE));
            }
			if (ClientConfig.PLATFORM != 0)
			{
				yield return new WaitForEndOfFrame();
			}
			if (isError)
			{
				Destroy();
			}
		}
		public override void Destroy()
		{
			base.Destroy();
			resource = null;
		}
	}
}
